package com.ops.service;

import com.ops.entity.OpsTask;
import com.ops.entity.Report;
import com.ops.entity.User;
import com.ops.entity.OpsRequest;
import com.ops.exception.BusinessException;
import com.ops.repository.ReportRepository;
import com.ops.repository.OpsRequestRepository;
import com.ops.repository.UserRepository;
import com.ops.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ReportService {
    
    @Autowired
    private ReportRepository reportRepository;
    
    @Autowired
    private OpsRequestRepository opsRequestRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 保存或更新报告信息
     * @param report 待保存的报告信息
     * @param username 创建者用户名
     * @return 保存后的报告信息
     * @throws BusinessException 当用户不存在时抛出异常
     */
    @Transactional
    public Report saveReport(Report report, String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("USER002", "用户不存在"));
        report.setCreatorUser(user.getUsername());
        // 根据唯一索引查找现有记录
        Optional<Report> existingTask = reportRepository.findByHospitalIdAndDemandYear(
                report.getHospitalId(), report.getDemandYear()
        );
        // 存在则更新
        if (existingTask.isPresent()) {
            LocalDateTime localDateTime = LocalDateTime.now();
            report.setId(existingTask.get().getId());
            report.setReportUuid(existingTask.get().getReportUuid());
            report.setCreateTime(localDateTime);
            report.setReportUrl(report.getReportUrl()+existingTask.get().getReportUuid());
        }else {
            String uuid = UUIDUtil.generateUUID();
            report.setReportUuid(uuid);
            report.setReportUrl(report.getReportUrl() + uuid);
        }
        return reportRepository.save(report);
    }
    
    /**
     * 根据报告ID获取报告信息
     * @param id 报告ID
     * @return 报告信息
     * @throws BusinessException 当报告不存在时抛出异常
     */
    @Transactional(readOnly = true)
    public Report getReport(Long id) {
        return reportRepository.findById(id)
            .orElseThrow(() -> new BusinessException("REPORT001", "报告不存在"));
    }
    
    /**
     * 根据报告UUID获取报告信息
     * @param uuid 报告UUID
     * @return 报告信息
     * @throws BusinessException 当报告不存在时抛出异常
     */
    @Transactional(readOnly = true)
    public Report getReportByUuid(String uuid) {
        return reportRepository.findByReportUuid(uuid)
            .orElseThrow(() -> new BusinessException("REPORT001", "报告不存在"));
    }
    
    /**
     * 获取指定报告中耗时最长的前N个需求
     * @param reportId 报告ID
     * @param limit 需求数量限制
     * @return 耗时最长的需求列表
     */
    public List<OpsRequest> getTopRequests(Long reportId, int limit) {
        return opsRequestRepository.findTopRequestsByReportId(reportId)
            .stream()
            .limit(limit).collect(Collectors.toList());
    }
    
    /**
     * 获取指定报告中最晚完成的需求
     * @param reportId 报告ID
     * @return 最晚完成的需求，如果不存在则返回null
     */
    public OpsRequest getLatestRequest(Long reportId) {
        return opsRequestRepository.findLatestRequestByReportId(reportId)
            .orElse(null);
    }
    
    /**
     * 根据医院ID和年度查询报告列表
     * @param hospitalId 医院ID，可选
     * @param year 年度，可选
     * @return 报告列表
     */
    @Transactional(readOnly = true)
    public List<Report> findReports(String hospitalId, String year) {
        if (hospitalId != null && !hospitalId.isEmpty() && year != null && !year.isEmpty()) {
            return reportRepository.findByHospitalIdAndDemandYearOrderByCreateTimeDesc(hospitalId, year);
        } else if (hospitalId != null && !hospitalId.isEmpty()) {
            return reportRepository.findByHospitalIdOrderByCreateTimeDesc(hospitalId);
        } else if (year != null && !year.isEmpty()) {
            return reportRepository.findByDemandYearOrderByCreateTimeDesc(year);
        } else {
            return reportRepository.findAllByOrderByCreateTimeDesc();
        }
    }
}